import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 * 
 *Conrol of CountReviews Thread 
 * Runs for librarians every 10 seconds, and Retreives the Unposted Review Count
 * If count changes, updates the counter in the main menu gui
 */

public class CountReviews extends Thread 
{
	/** Indicate Unposted Review Count*/ 
	public Integer UnpostedReviewsCount;
	MainScreen mainScreen;
		/**
	 * This is the default constructor
	 * at first login , sets the count to -1 (as a flag)
	 */
	public CountReviews(MainScreen mainScr) 
	{
		this.mainScreen=mainScr;
		UnpostedReviewsCount=-1;
	}
	
		/**
	 * This is the runnable method : Sleeps every 10 secs and retreives count from DB
	 * If count changes, updates the counter in the main menu gui
	 */
	public void run() 
	{
		mainScreen.panel.add(getSubjectText(), null);		
			while(true)
			{
				mainScreen.panel.remove(mainScreen.ReviewCountTxt);
				mainScreen.panel.add(getSubjectText(), null);
				mainScreen.panel.validate();
				mainScreen.panel.repaint();
				try {
					sleep(10000);		//Every 10 seconds
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
    }
	
	/**
	 * This method initializes SubjectText for the main menu gui
	 * 	
	 * @return javax.swing.JTextField	
	 */
	JTextField getSubjectText() 
	{					
		mainScreen.ReviewCountTxt = new JTextField(GetReviewCount());
		mainScreen.ReviewCountTxt.setFont(new Font("David",Font.BOLD,18));
		mainScreen.ReviewCountTxt.setBounds(new Rectangle(350, 293, 40, 26));
		mainScreen.ReviewCountTxt.setBackground(Color.LIGHT_GRAY);
		mainScreen.ReviewCountTxt.setEditable(false);	
		mainScreen.ReviewCountTxt.setHorizontalAlignment(JTextField.CENTER);
		return mainScreen.ReviewCountTxt;
	}
	/**
	 * This method Send a Request to DB to retreive the Unposted Review Count
	 * 	
	 * @return String with the updated count
	 */
	String GetReviewCount()
	{
		String temp;
		mainScreen.ReviewCount=new String[2];
		mainScreen.ReviewCount[0]=Main.gusers.id;
		mainScreen.ReviewCount[1]="getReviewCount";				
		Main.log.connection.accept("getReviewCount");
		Main.log.flag2=false;
		while(Main.log.flag2==false);
		Main.log.flag2=false;		
		temp=ChatClient.getRs2();
		if (UnpostedReviewsCount!=-1) 
		{
			if (Integer.parseInt(temp)>UnpostedReviewsCount)
				JOptionPane.showMessageDialog(null, " New User Review/s have Been posted ! ","Database message" ,JOptionPane.INFORMATION_MESSAGE);			
		}
		UnpostedReviewsCount=Integer.parseInt(temp);
		return temp;
	}	

}
